var table;
var isDivHiden;

$(document).ready(function () {
    isDivHiden = true;
    $('#divAddNewCar').hide();

    table = $('#table_cars').DataTable({
        ajax: {
            url: "/Trabalho_PD/webresources/WebServiceBoleias/getAllCarsFromUser/" + user_id,
            type: "GET",
            dataSrc: "cars"
        },
        columns: [
            {data: 'brand'},
            {data: 'seats'},
            {data: 'year'},
            {data: 'plate_number'},
            {
                "className": 'edit-control',
                "orderable": false,
                "data": null,
                "defaultContent": '<i class="btn btn-success fa fa-pencil-square-o fa-2x"></i>'
            },
            {
                "className": 'delete-control',
                "orderable": false,
                "data": null,
                "defaultContent": '<i class="btn btn-danger fa fa-trash-o fa-2x"></i>'
            },
            {
                "className": 'details-control',
                "orderable": false,
                "data": null,
                "defaultContent": '<i class="btn btn-info fa fa-plane fa-2x"></i>'
            }
        ]

    });

    $('#table_cars tbody').on('click', 'td.details-control', function () {
        var tr = $(this).closest('tr');
        var row = table.row(tr);

        if (row.child.isShown()) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        }
        else {
            // Open this row
            var rowData = row.data();
            if (rowData) {
                var child = row.child(createShowTripsHtml(rowData));
                child.show();
                tr.addClass('shown');

                $("#table_" + rowData.id_car).DataTable({
                    ajax: {
                        url: "/Trabalho_PD/webresources/WebServiceBoleias/getAllTripsFromCar/" + rowData.id_car,
                        type: "GET",
                        dataSrc: "trip"
                    },
                    columns: [
                        {
                            orderable: false,
                            data: function (row, type, val, meta) {
                                if (row.ended) {
                                    return true;
                                } else {
                                    return false;
                                }
                            },
                            render: function (data, type, full, meta) {
                                if (data) {
                                    return '<span class="positive"><i class="fa fa-check fa-2x"></i></span>';
                                } else {
                                    return '<span class="warning"><i class="fa fa-tag fa-2x"></i></span>';
                                }
                            }
                        },
                        {data: 'departueDate'},
                        {data: 'departue_address'},
                        {data: 'destination_address'},
                        {
                            orderable: false,
                            data: function (row, type, val, meta) {
                                return row.id_trip;
                            },
                            render: function (data, type, full, meta) {
                                return '<a class="btn btn-info" href="/Trabalho_PD/tripinformation.html?id=' + data + '"><i class="fa fa-search fa-2x"></i></a>';
                            }
                        }
                    ]

                });
            }

        }
    });

    $('#table_cars tbody').on('click', 'td.edit-control', function () {
        var tr = $(this).closest('tr');
        var row = table.row(tr);

        if (row.child.isShown()) {
            // This row is already open - close it
            row.child.hide();
            tr.removeClass('shown');
        }
        else {
            // Open this row
            row.child(createEditCarHtml(row.data(), row.index())).show();
            tr.addClass('shown');
        }
    });

    $('#table_cars tbody').on('click', 'td.delete-control', function () {
        var tr = $(this).closest('tr');
        var id_car = table.row(tr).data().id_car;
        sendRemoveCar(id_car, function (data) {
            if (data["success"]) {
                table.row(tr).remove().draw();
            }
        });
    });
});


function createShowTripsHtml(d) {
    // `d` is the original data object for the row
    return '<table id="table_' + d.id_car + '" class="table table-striped table-bordered">' +
            '<thead>' +
            '<tr>' +
            '<th></th>' +
            '<th>Departure Date</th>' +
            '<th>Departure</th>' +
            '<th>Destination</th>' +
            '<th></th>' +
            '</tr>' +
            '</thead>' +
            '<tbody>' +
            '</tbody>' +
            '</table>';
}

function createEditCarHtml(d, i) {
    // `d` is the original data object for the row
    return '<form id="form_' + d.id_car + '" class="form-horizontal">' +
            '<div class="form-group">' +
            '<label class="col-xs-12 col-sm-2">Seats</label>' +
            '<div class="col-xs-12 col-sm-10">' +
            '<input type="number" class="form-control" minlength="1" maxlength="2" name="seats" value="' + d.seats + '" placeholder="Number of car seats" data-error="Number of seats must have 1-2 numbers!" />' +
            '</div>' +
            '</div>' +
            '<div class="form-group">' +
            '<label class="col-xs-12 col-sm-2">Plate Number</label>' +
            '<div class="col-xs-12 col-sm-10">' +
            '<input type="text" class="form-control" minlength="1" maxlength="10" name="plate_number" value="' + d.plate_number + '" placeholder="Car plate number" data-error="Plate number must have 1-10 characters!" />' +
            '</div>' +
            '</div>' +
            '<div class="form-group">' +
            '<label class="col-xs-12 col-sm-2">Brand</label>' +
            '<div class="col-xs-12 col-sm-10">' +
            '<input type="text" class="form-control" minlength="1" maxlength="70" name="brand" value="' + d.brand + '" placeholder="Car brand" data-error="Brand must have 1-70 characters!"/>' +
            '</div>' +
            '</div>' +
            '<div class="form-group">' +
            '<label class="col-xs-12 col-sm-2">Year</label>' +
            '<div class="col-xs-12 col-sm-10">' +
            '<input type="number" class="form-control" minlength="4" maxlength="4" name="year" value="' + d.year + '" placeholder="Year of car production" data-error="Year must have 4 numbers!"/>' +
            '</div>' +
            '</div>' +
            '<div class="form-group">' +
            '<div class="col-xs-12">' +
            '<button type="button" onclick="editCarClick(\'' + d.id_car + '\',\'' + i + '\')" class="btn btn-primary">Edit car</button>' +
            '</div>' +
            '</div>' +
            '</form>';
}

function moreButtonClick() {
    if (isDivHiden) {
        $('#divAddNewCar').show(2000);
        $('#moreButton').html('<i class="fa fa-minus"></i>');
        isDivHiden = false;
    }
    else {
        $('#divAddNewCar').hide(1000);
        $('#moreButton').html('<i class="fa fa-plus"></i>');
        isDivHiden = true;
    }
}

function editCarClick(form, i) {
    if (myValidatorValidate('form_' + form)) {
        var data = myValidatorReadForm('form_' + form);
        sendEditCar(form, data[0].val, data[1].val, data[2].val, data[3].val, function (readData) {
            if (readData["success"] !== -1) {
                var newCar = {id_car: form, brand: data[2].val, seats: data[0].val, year: data[3].val, plate_number: data[1].val};
                table.row(i).data(newCar).draw();
            }
        });
    }
}

function addNewCarClick() {
    if (myValidatorValidate('formAddNewCar')) {
        var car = myValidatorReadForm('formAddNewCar');
        sendCreateCar(car[0].val, car[1].val, car[2].val, car[3].val, function (readData) {
            if (readData["success"] !== -1) {
                getCar(readData["success"], function (newCar) {
                    table.row.add(newCar).draw();
                    $('#divAddNewCar').hide(1000);
                    $('#moreButton').html('More');
                    isDivHiden = true;
                });
            }
        });
    }
}